package com.smilive.delay.queue.jvm;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @program: delay_queue_start
 * @Date: 2022-02-08 14:10
 * @Author: smilive
 * @Description: DelayQueue只能添加(offer/put/add)实现了Delayed接口的对象
 */
@Slf4j
public class JvmDelayQueue {

    public static void main(String[] args) throws InterruptedException {
        //延迟队列
        DelayQueue<JvmDelayTask> queue = new DelayQueue<>();
        //默认3秒
        JvmDelayTask task = new JvmDelayTask(1);
        queue.add(task);
        //默认5秒
        task = new JvmDelayTask(2,5);
        queue.add(task);
        //默认10秒
        task = new JvmDelayTask(3,10);
        queue.add(task);

        ExecutorService executorService = Executors.newSingleThreadExecutor(r -> {
            Thread thread = new Thread(r);
            thread.setName("DelayTask");
            thread.setDaemon(true);
            return thread;
        });
        log.info("开始执行延迟任务...");
        executorService.execute(() -> {
            while (true){
                try {
                    JvmDelayTask take = queue.take();
                    log.info("延迟任务信息:{}",take.getDescription());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread.sleep(Integer.MAX_VALUE);

    }
}
